const {findOne, signup:sign} = require("../models/administrator");
const { compare, sign:tksign, vertify } = require("../utils/tools");

const signup = async (req, res, next) => {
    res.set('content-type', 'application/json; charset=utf-8')

    const {username, password} = req.body

    const flag = await findOne(username)
    if(flag) {
        res.render('fail', {
            data: JSON.stringify({
                flag: flag,
                msg: '用户名重复',
            })
        })
    } else {
        const msg = await sign(username, password)
        res.render('succ', {
            data: JSON.stringify(msg)
        })
    }
}

const signin = async (req, res, next) => {
    res.set('content-type', 'application/json; charset=utf-8')

    const {username, password} = req.body

    const administrator = await findOne(username)
    if(administrator && await compare(password, administrator.password)) {
        const tk = tksign(username)
        res.set('Y-Access-Token', tk)
        res.render('succ', {
            data: JSON.stringify({
                msg: '登录成功',
                user: administrator
            })
        })
    } else {
        res.render('fail', {
            data: JSON.stringify('用户名或密码错误')
        })
    }
}

const isAuth = async (req, res, next) => {
    res.set('content-type', 'application/json; charset=utf-8')

    const tk = req.get('Y-Access-Token')
    console.log(tk, vertify(tk))
    if(vertify(tk)) {
        res.render('succ', {
            data: JSON.stringify(true)
        })
    } else {
        res.render('fail', {
            data: JSON.stringify(false)
        })
    }
}

module.exports = {
    signup,
    signin,
    isAuth,
}